<template>
    <BasePage>
        <el-form slot="form" :inline="true" size="medium">
            <el-form-item label="巡查类型">
                <el-select v-model="query.type" clearable placeholder="请选择" style="width: 100%">
                    <el-option v-for="item in patrolType" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="缺陷病害类型">
                <el-select v-model="query.defectDiseaseType" clearable placeholder="请选择" style="width: 100%">
                    <el-option v-for="item in DefectDiseaseTypeOptions" :key="item.value" :label="item.label" :value="item.label" />
                </el-select>
            </el-form-item>
            <el-form-item label="公路名称">
                <RoadSelect :value.sync="query.highwayCode" clearable></RoadSelect>
            </el-form-item>
            <el-form-item label="巡查日期：">
                <el-date-picker
                    v-model="query.inspectDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    :editable="false"
                    style="width: 100%"
                    placeholder="选择日期"
                    clearable
                />
            </el-form-item>
            <el-form-item>
                <BaseButton v-permission="{ btnCode: 'dlyh_c10_d26_2' }" @click="handleFilter">查询</BaseButton>
                <BaseButton type="second" @click="resetConditions()">重置</BaseButton>
            </el-form-item>
        </el-form>
        <div slot="button">
            <BaseButton v-permission="{ btnCode: 'dlyh_c10_d28_2' }" @click="handleAdd"> 新增缺陷病害 </BaseButton>
            <BaseButton v-permission="{ btnCode: 'dlyh_c10_d33_2' }" :disabled="!selectedList.length" @click="handleAddProject('main')"> 批量生成养护工程 </BaseButton>
            <BaseButton v-permission="{ btnCode: 'dlyh_c10_d385_2' }" :disabled="!selectedList.length" @click="handleAddProject('task')"> 批量生成养护任务单 </BaseButton>
        </div>
        <BaseTable
            slot="table"
            ref="table"
            v-loading="listLoading"
            :data="list"
            row-key="number"
            :columns="columns"
            highlight-current-row
            height="calc(100% - 73px)"
            @selection-change="handleSelectionChange"
        >
            <template #number="{ scope: { row } }">
                <BaseButton type="text" @click="detail(row.id, row.createUserName)">{{ row.number }}</BaseButton>
            </template>
            <template #status="{ scope: { row } }">
                <span :class="row.status === 1 ? 'color-red' : ''">{{ states[row.status] }}</span>
            </template>
            <template #action="{ scope: { row } }">
                <BaseButton v-show="row.status === 1" v-permission="{ btnCode: 'dlyh_c10_d31_2' }" type="text" @click="result(row)"> 填写处理记录 </BaseButton>
                <BaseButton v-show="row.status === 1" v-permission="{ btnCode: 'dlyh_c10_d32_2' }" type="text" @click="project('main', row)"> 生成养护工程 </BaseButton>
                <BaseButton v-show="row.status === 1" v-permission="{ btnCode: 'dlyh_c10_d386_2' }" type="text" @click="project('task', row)"> 创建养护任务单 </BaseButton>
                <BaseButton v-show="row.status === 2" v-permission="{ btnCode: 'dlyh_c10_d29_2' }" type="text" @click="handleViewResult(row)">
                    查看处理结果
                </BaseButton>
                <BaseButton v-show="row.status === 3" v-permission="{ btnCode: 'dlyh_c10_d30_2' }" type="text" @click="toMaintProject(row.maintProjectCode)">{{
                    row.maintProjectCode
                }}</BaseButton>
                <BaseButton v-show="row.status === 4" v-permission="{ btnCode: 'dlyh_c10_d384_2' }" type="text" @click="toTaskProject(row.maintTaskCode)">{{
                    row.maintTaskCode
                }}</BaseButton>
                <BaseButton v-permission="{ btnCode: 'dlyh_c10_d383_2' }" :disabled="row.status !== 1 || row.createUser !== $store.getters.avatar.id" type="text" color="danger" @click="handleDelete(row.id)">删除</BaseButton>
            </template>
        </BaseTable>
        <Pagination
            slot="pagination"
            class="text-right"
            :current-page.sync="page.pageNo"
            :page-size.sync="page.pageSize"
            :total="page.total"
            @size-change="getList"
            @current-change="getList"
        />
        <el-dialog :visible.sync="dialogVisible" title="填写处理记录" width="46%">
            <el-form ref="resultForm" :model="resultForm" :rules="resultRules">
                <el-form-item label="处置结果：" prop="handleRecord">
                    <el-input v-model="resultForm.handleRecord" type="textarea" placeholder="请输入" :rows="3" maxlength="300" show-word-limit></el-input>
                </el-form-item>
                <el-form-item>
                    <span> 图片上传</span><span style="font-size: 10px; color: #999; margin-left: 10px">最多可上传10张</span>
                    <ImageUpload ref="imageUpload" :list.sync="resultForm.handlePhotos"></ImageUpload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="confirm">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog :visible.sync="dialogdetailVisible" title="处理记录" width="40%">
            <el-form ref="resultForm">
                <div style="margin-bottom: 12px">
                    <span>处置结果：</span>
                    <div>
                        {{ activeRow.handleRecord }}
                    </div>
                </div>
                <div>
                    <span> 图片：</span>
                    <div class="demo-image__preview">
                        <el-image
                            v-for="(item, index) in activeRow.handlePhotos"
                            :key="index"
                            style="width: 100px; height: 100px; margin-right: 8px"
                            :src="item"
                            :preview-src-list="activeRow.handlePhotos"
                            :z-index="99999"
                        >
                        </el-image>
                    </div>
                </div>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogdetailVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogdetailVisible = false">确 定</el-button>
            </span>
        </el-dialog>
    </BasePage>
</template>

<script>
import BasePage from '@/layouts/BasePage'
import { InspectionDefectRecordModel } from '@/models'
import useSuccess from '@/hooks/useSuccess'
import { patrolType } from '../../constants'
import KeepAliveHandler from '@/mixins/keepAliveHandler'
import storage, { get } from 'good-storage'
import { DefectDiseaseTypeOptions } from '@/views/maintenance-decision/constants'
import reconfirm from '@/utils/reconfirm'

export default {
    name: 'FlawList',
    components: {
        BasePage
    },
    mixins: [
        KeepAliveHandler({
            defaultCondition: {
                type: null,
                defectDiseaseType: null,
                highwayCode: null,
                inspectDate: null
            },
            conditionObjKey: 'query'
        })
    ],
    data() {
        return {
            DefectDiseaseTypeOptions,
            model: new InspectionDefectRecordModel(),
            dialogVisible: false,
            dialogdetailVisible: false,
            previewSrc: '',
            page: {
                pageNo: 1,
                pageSize: 10,
                total: 0
            },
            listLoading: false,
            columns: [
                {
                    attrs: {
                        type: 'selection',
                        selectable: (row) => {
                            return row.status === 1
                        },
                        'reserve-selection': true
                    }
                },
                {
                    slot: 'number',
                    attrs: {
                        label: '编号',
                        width: '140',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        label: '巡查类型',
                        prop: 'typeName',
                        'show-overflow-tooltip': true,
                        width: '180'
                    }
                },
                {
                    attrs: {
                        label: '上报人',
                        prop: 'createUserName',
                        'show-overflow-tooltip': true,
                        'min-width': '140'
                    }
                },
                {
                    attrs: {
                        label: '巡查部门',
                        prop: 'deptName',
                        'show-overflow-tooltip': true,
                        'min-width': '160'
                    }
                },
                {
                    attrs: {
                        label: '缺陷病害类型',
                        prop: 'defectDiseaseType',
                        'show-overflow-tooltip': true,
                        'min-width': '120'
                    }
                },
                {
                    attrs: {
                        label: '巡查日期',
                        prop: 'inspectDate',
                        width: '130',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        label: '公路名称',
                        prop: 'highwayName',
                        width: '130',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        label: '位置类型',
                        prop: 'locationTypeName',
                        width: '140',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        label: '位置/桩号',
                        prop: 'location',
                        width: '160',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        label: '问题描述',
                        prop: 'abnormalDescription',
                        'show-overflow-tooltip': true,
                        'min-width': '140'
                    }
                },
                {
                    slot: 'status',
                    attrs: {
                        label: '状态',
                        prop: 'status',
                        width: '120',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    slot: 'action',
                    attrs: {
                        label: '操作',
                        fixed: 'right',
                        width: '380'
                    }
                }
            ],
            resultForm: {
                handlePhotos: []
            }, // 处理结果
            list: [],
            query: {},
            states: {
                1: '待处理',
                2: '现场处理',
                3: '工程处理',
                4: '工单处理'
            },
            selectedList: [],
            activeRow: {
                handlePhotos: []
            },
            resultRules: { handleRecord: [{ required: true, message: '请输入处理记录', trigger: 'blur' }] }
        }
    },
    computed: {
        patrolType() {
            return patrolType
        }
    },
    mounted() {
        this.getList()
    },
    methods: {
        cancel() {
            // 清除表单
            this.resultForm = {}
            this.resultForm.handlePhotos = []
            this.dialogVisible = false
        },
        confirm() {
            const data = {
                handleRecord: this.resultForm.handleRecord
            }
            if (this.resultForm.handlePhotos && this.resultForm.handlePhotos.length) {
                data.handlePhotos = this.resultForm.handlePhotos
                    .map((item) => {
                        return item.response.data.objectUrl
                    })
                    .join(',')
            } else {
                data.handlePhotos = ''
            }
            this.$refs['resultForm'].validate(async (valid) => {
                if (valid) {
                    this.model.saveOrUpdate({ id: this.activeRow.id, ...data }).then((res) => {
                        useSuccess({ message: '更新成功', onlyTip: true })
                        this.dialogVisible = false
                        this.handleFilter()
                        // 清除表单
                        this.resultForm = {}
                        this.resultForm.handlePhotos = []
                    })
                }
            })
        },
        handleFilter() {
            this.page.pageNo = 1
            this.getList()
        },
        handleSelectionChange(val) {
            this.selectedList = val
        },
        handleAdd() {
            this.$router.push({
                path: './add'
            })
        },
        handleDelete(id) {
            reconfirm({
                text: '是否删除当前数据',
                callback: () => {
                    return this.model.delete({ id }).then(() => {
                        this.getList()
                        this.$message.success('删除成功!')
                    })
                }
            })
        },
        handleAddProject(type) {
            console.log(111111)
            let name = ''
            if (type === 'main') {
                name = 'MaintenanceProjectAdd'
            }
            if (type === 'task') {
                name = 'DailyMaintenanceTaskAdd'
                // 如果所选缺陷来自不同公路禁止跳转
                const higways = new Set(this.selectedList.map(el => el.highwayCode))
                if (Array.from(higways).length > 1) {
                    this.$message.warning('只能选择同一条公路的缺陷病害')
                    return false
                }
            }
            this.$router.push({
                name,
                query: {
                    source: 'FlawList'
                }
            })
            storage.set('flaws', this.selectedList)
        },
        // 生成单个养护工程
        project(type, row) {
            let name = ''
            if (type === 'main') {
                name = 'MaintenanceProjectAdd'
            }
            if (type === 'task') {
                name = 'DailyMaintenanceTaskAdd'
            }
            this.$router.push({
                name,
                query: {
                    source: 'FlawList'
                }
            })
            storage.set('flaws', [{ ...row }])
        },
        result(row) {
            this.dialogVisible = true
            this.activeRow = row
        },
        handleViewResult(row) {
            this.dialogdetailVisible = true
            this.activeRow = row
            this.activeRow.handlePhotos = row.handlePhotos ? row.handlePhotos.split(',') : []
        },
        detail(id, createUserName) {
            this.$router.push({
                path: './detail',
                query: { id, createUserName }
            })
        },
        getList() {
            this.listLoading = true
            this.model
                .getList(this.query, this.page)
                .then((res) => {
                    this.list = res.list
                    this.page.total = res.totalCount
                })
                .finally(() => {
                    this.listLoading = false
                })
        },
        // 取到养护工程详情页
        toMaintProject(code) {
            this.$router.push({
                name: 'MaintenanceProjectDetail',
                query: {
                    number: code
                }
            })
        },
        toTaskProject(code) {
            this.$router.push({
                name: 'DailyMaintenanceTaskDetail',
                query: {
                    number: code
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
</style>
